var qcloud = require('../../vendor/wafer2-client-sdk/index')
var config = require('../../config')
var util = require('../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    disabled: false,
    titlefocus: false,
    functype: '',
    userinfo: '',
    seqid: '',
    activity: '',
    imageurl: '',
    title: '',
    indexing: '',
    author: '',
    elements: [{ value: '0', name: '文本' }, { value: '1', name: '图片' }],//, { value: '4', name: '视频' }, { value: '3', name: '音频' }
    //textStyleIndex:[0,0,0],//颜色，大小，换行
    textStyle: [
      [{ value: '0', name: '黑色' }, { value: '1', name: '灰色' }, { value: '2', name: '红色' }, { value: '3', name: '蓝色' }],
      [{ value: '0', name: '正文' }, { value: '1', name: '标题' }, { value: '2', name: '备注' }],
      [{ value: '0', name: '换行' }, { value: '1', name: '不换行' }]
    ],
    imageStyle: [{ value: '0', name: '黄金比例(1.618：1)' }, { value: '1', name: '2：1' }, { value: '2', name: '4：3' }, { value: '3', name: '1：1' },],//长宽比
    articleDetails: [{}],//[{"openid":"|r_openid|","seqid":"", "orders":"","elmttype":"","elmtvalue":"","style":""},{}]

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this;
    var seqid = self.options.seqid;
    if (seqid && seqid != '' && seqid != undefined) {
      qcloud.request({
        url: `${config.service.host}/weapp/articleManage`,
        method: 'POST',
        data: { opflag: '1', openid: self.options.openid, seqid: seqid }, //opflag 0获取列表 1查看明细 2新增 3更新 4删除
        login: true,
        success(result) {
          if (result.data.data.status == '0') {
            var publishdate = util.formatDate(result.data.data.msg.updatetime);

            var articleDetails = result.data.data.msg.detaildata;
            for (var i = 0; i < articleDetails.length; i++) {
              articleDetails[i].style = JSON.parse(articleDetails[i].style);
            }
            self.setData({
              activity: result.data.data.msg.activity,
              title: result.data.data.msg.title,
              indexing: result.data.data.msg.indexing,
              author: result.data.data.msg.author,
              userinfo: result.data.data.userinfo,
              updatetime: publishdate,
              articleDetails: articleDetails,
              seqid: seqid,
              functype: self.options.functype
            })
          } else {
            console.log('add acticle error:', result.data.data);
          }
        },
        fail(error) {
          console.log('request fail', error);
          util.relogin(self);
        }
      })

    } else {

      qcloud.request({
        url: `${config.service.host}/weapp/articleManage`,
        method: 'POST',
        data: { opflag: '2', functype: self.options.functype }, //opflag 0获取列表 1查看明细 2新增 3更新 4删除
        login: true,
        success(result) {
          if (result.data.data.status == '0') {
            var articleDetails = [{ "openid": result.data.data.userinfo.openId, "seqid": result.data.data.msg.seqid, "orders": "", "elmttype": "0", "elmtvalue": "", "style": [0, 0, 0] }];
            self.setData({
              seqid: result.data.data.msg.seqid,
              activity: result.data.data.msg.activity,
              userinfo: result.data.data.userinfo,
              articleDetails: articleDetails,
              functype: self.options.functype
            })
          } else {
            console.log('add acticle error:', result.data.data);
          }
        },
        fail(error) {
          console.log('request fail', error);
          util.relogin(self);
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //要素选择触发
  elementChange: function (e) {
    var articleDetails = this.data.articleDetails;
    articleDetails[e.currentTarget.id].elmttype = e.detail.value;
    articleDetails[e.currentTarget.id].elmtvalue = '';
    this.setData({
      articleDetails: articleDetails
    })
  },
  //文本选择触发
  textColumnChange: function (e) {
    //console.log(e.detail);
    var articleDetails = this.data.articleDetails;
    articleDetails[e.currentTarget.id].style[e.detail.column] = e.detail.value * 1;

    this.setData({
      articleDetails: articleDetails
    })
  },
  textChange: function (e) {
    // e.detail.column,  e.detail.value
    //console.log(e.detail);
    // this.setData({
    //   elementIndex: e.detail.value
    // })
  },
  imageChange: function (e) {
    var articleDetails = this.data.articleDetails;
    articleDetails[e.currentTarget.id].style[0] = e.detail.value * 1;
    this.setData({
      articleDetails: articleDetails
    })
  },
  //文章内容选图
  chooseImage: function (e) {
    var self = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed', 'original'],
      sourceType: ['camera', 'album'],
      success: function (res) {
        console.log('chooseImage success, temp path is', res.tempFilePaths[0])
        var imageSrc = res.tempFilePaths[0];
        // var articleDetails = self.data.articleDetails;
        // articleDetails[e.currentTarget.id].elmtvalue = imageSrc;
        // self.setData({
        //   articleDetails: articleDetails
        // })
        wx.uploadFile({
          url: `${config.service.host}/weapp/articleFileUpload`,
          filePath: imageSrc,
          name: 'userupload',
          success: function (result) {
            result = JSON.parse(result.data)
            if (result.data.status == '0') {
              var articleDetails = self.data.articleDetails;
              articleDetails[e.currentTarget.id].elmtvalue = result.data.msg.imgUrl;
              self.setData({
                articleDetails: articleDetails
              })
            } else {
              util.showBusy(result.data.msg)
              // wx.showToast({
              //   title: result.data.msg,
              //   icon: 'loading',
              //   // duration: 1000
              // })
            }
            // {
            //   imgUrl: string,     // 图片访问地址
            //     size: number,       // 图片大小
            //       mimeType: string,   // 图片 MIME 类型
            //         name: string        // 图片名称
            // }
          },
          fail: function ({ errMsg }) {
            util.showBusy(errMsg);
            // wx.showToast({
            //   title: errMsg,
            //   icon: 'loading',
            //   // duration: 1000
            // })
          }
        })
      },
      fail: function ({ errMsg }) {
        util.showBusy(errMsg);
        // wx.showToast({
        //   title: errMsg,
        //   icon: 'loading',
        //   // duration: 1000
        // })
      }
    })
  },
  //选择文章缩略图
  imageurlChange: function () {
    var self = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera', 'album'],
      success: function (res) {
        console.log('chooseImage success, temp path is', res.tempFilePaths[0])
        var imageSrc = res.tempFilePaths[0];
        // self.setData({
        //   imageurl: imageSrc
        // })
        wx.uploadFile({
          url: `${config.service.host}/weapp/articleFileUpload`,
          filePath: imageSrc,
          name: 'userupload',
          success: function (result) {
            result = JSON.parse(result.data)
            if (result.data.status == '0') {
              self.setData({
                imageurl: result.data.msg.imgUrl
              })
            } else {
              util.showBusy(result.data.msg);
              // wx.showToast({
              //   title: result.data.msg,
              //   icon: 'loading',
              //   // duration: 1000
              // })
            }
            // {
            //   imgUrl: string,     // 图片访问地址
            //     size: number,       // 图片大小
            //       mimeType: string,   // 图片 MIME 类型
            //         name: string        // 图片名称
            // }
          },
          fail: function ({ errMsg }) {
            util.showBusy(errMsg);
            // wx.showToast({
            //   title: errMsg,
            //   icon: 'loading',
            //   // duration: 1000
            // })
          }
        })
      },
      fail: function ({ errMsg }) {
        util.showBusy(errMsg);
        // wx.showToast({
        //   title: errMsg,
        //   icon: 'loading',
        //   // duration: 1000
        // })
      }
    })
  },
  bindAdd: function () {
    var articleDetails = this.data.articleDetails;
    articleDetails = articleDetails.concat([{ "openid": this.data.userinfo.openId, "seqid": this.data.seqid, "orders": "", "elmttype": "0", "elmtvalue": "", "style": [0, 0, 0] }]);

    this.setData({
      articleDetails: articleDetails
    })
  },

  formSubmit: function (e) {
    //标题必填 作者未填默认微信名 内容未填直接删
    var self = this;
    var title = e.detail.value.title;
    if (title.trim() == '') {
      wx.showModal({
        title: '提示',
        content: '请输入标题',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            self.setData({
              titlefocus: true
            })
          }
        }
      })
    } else {
      //内容未填提示删除
      var todelIndex = '';
      var articleDetails = this.data.articleDetails;
      var editseq = '';
      for (var i = 0; i < articleDetails.length; i++) {
        if (articleDetails[i].elmtvalue.trim() == '' || articleDetails[i].elmtvalue.trim() == undefined) {
          todelIndex = todelIndex.concat(i);
          editseq = editseq.concat(' ' + (i + 1) + ' ');
        }
      }
      //console.log(todelIndex);
      //定义插表数据
      var toupdate = function () {
        //console.log("data format")
        self.setData({
          loading: !self.data.loading,
          disabled: !self.data.disabled
        })
        //删除无效数据，更新orders，提交数据
        for (var i = todelIndex.length - 1; i >= 0; i--) {
          articleDetails.splice(todelIndex[i], 1);
        }
        for (var i = 0; i < articleDetails.length; i++) {
          articleDetails[i].orders = i;
          articleDetails[i].style = JSON.stringify(articleDetails[i].style);
          delete articleDetails[i].updatetime;
        }
        var submitData = { "opflag": "3", "openid": self.data.userinfo.openId, "seqid": self.data.seqid, "functype": self.data.functype, "organize": "ALL", "activity": "", "title": title, "indexing": e.detail.value.indexing, "author": e.detail.value.nickName ? e.detail.value.nickName : self.data.userinfo.nickName, "imageurl": e.detail.value.imageurl ? e.detail.value.imageurl : self.data.userinfo.avatarUrl, "authority": "", "enddate": "", "detaildata": articleDetails };
        //console.log(submitData)

        //发起录入请求
        qcloud.request({
          url: `${config.service.host}/weapp/articleManage`,
          method: 'POST',
          data: submitData, //opflag 0获取列表 1查看明细 2新增 3更新 4删除
          login: true,
          success(result) {
            if (result.data.data.status == '0') {
              console.log('update acticle succed:', result.data.data);
              //util.showSuccess('信息维护成功');
              // wx.showToast({
              // title: '信息维护成功',
              // icon: 'success',
              // // duration: 1000
              // })
              wx.redirectTo({
                url: '/pages/functions/articledetail?functype=' + self.data.functype + '&openid=' + self.data.userinfo.openId + '&seqid=' + self.data.seqid
              })
            } else {
              console.log('update acticle error:', result.data.data);
              util.showBusy(result.data.data.msg);
              // wx.showToast({
              //   title: result.data.data.msg,
              //   icon: 'loading',
              //   // duration: 1000
              // })
              self.setData({
                loading: !self.data.loading,
                disabled: !self.data.disabled
              })
            }
          },
          fail(error) {
            console.log('request fail', error);
            util.relogin(self);
          }
        })
      }
      if (todelIndex.length == articleDetails.length) {
        util.showModel('提示', '至少要录入一条信息内容，请录入');
      } else if (todelIndex[0]) {
        wx.showModal({
          title: '提示',
          content: '排版顺序为' + editseq + '的信息未录入，系统将自动删除该排版信息，是否继续？',
          success: function (res) {
            if (res.confirm) {
              toupdate();
            } else
              if (res.cancel) {
                console.log("cancel")
                return;
              }
          }
        })
      } else {
        toupdate();
      }
    }

  },
  // formReset(){

  // },
  // elmtmove(e){
  //   console.log('elmtmove', e)
  //   var articleDetails = this.data.articleDetails;
  //   articleDetails[e.currentTarget.id].elmtvalue = `e.detail.area${e.currentTarget.id}.value`;
  //   this.setData({
  //     articleDetails: articleDetails
  //   })
  // },
  elmtup: function (e) {

    var articleDetails = this.data.articleDetails;
    var index = e.currentTarget.id;
    if (index == 0) {
      return;
    }
    var target = [];
    for (var i = 0; i < articleDetails.length; i++) {
      if (i == index - 1) {
        target = target.concat(articleDetails[i + 1]).concat(articleDetails[i]);
        i++;
      } else {
        target = target.concat(articleDetails[i]);
      }
    }
    this.setData({
      articleDetails: target
    })
    this.elmtdel(e)
  },
  elmtdown: function (e) {
    var articleDetails = this.data.articleDetails;
    var index = e.currentTarget.id;
    if (index == articleDetails.length - 1) {
      return;
    }
    var target = [];
    for (var i = 0; i < articleDetails.length; i++) {
      if (i == index) {
        target = target.concat(articleDetails[i + 1]).concat(articleDetails[i]);
        i++;
      } else {
        target = target.concat(articleDetails[i]);
      }
    }
    this.setData({
      articleDetails: target
    })
  },
  elmtdel: function (e) {
    var articleDetails = this.data.articleDetails;
    var index = e.currentTarget.id;
    if (index == 0 && articleDetails.length == 1) {
      return;
    }
    articleDetails.splice(index, 1);
    this.setData({
      articleDetails: articleDetails
    })
  },
  bindareablur: function (e) {
    var articleDetails = this.data.articleDetails;
    articleDetails[e.currentTarget.id].elmtvalue = e.detail.value;
    this.setData({
      articleDetails: articleDetails,
      disabled: false
    })
  },
  bindareafocus: function (e) {
    this.setData({
      disabled: true
    })
  },

})